package com.zhuhjay.ucenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuhjay.commonutils.JwtUtils;
import com.zhuhjay.servicebase.exception.GuLiException;
import com.zhuhjay.ucenter.entity.Member;
import com.zhuhjay.ucenter.entity.wx.AccessTokenInfo;
import com.zhuhjay.ucenter.entity.wx.UserInfo;
import com.zhuhjay.ucenter.prop.WxOpenProperties;
import com.zhuhjay.ucenter.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URLEncoder;


@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Resource
    private MemberService memberService;

    @Resource
    private WxOpenProperties wxOpenProperties;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("callback")
    public String callback(String code, String state) {
        try {
            //1 获取code值，临时票据，类似于验证码
            //2 拿着code请求 微信固定的地址，得到两个值 accsess_token 和 openid
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            //拼接三个参数 ：id  秘钥 和 code值
            String accessTokenUrl = String.format(
                    baseAccessTokenUrl,
                    wxOpenProperties.getAppId(),
                    wxOpenProperties.getAppSecret(),
                    code);
            //请求这个拼接好的地址，得到返回两个值 accsess_token 和 openid
            //使用httpclient发送请求，得到返回结果
            AccessTokenInfo tokenInfo = restTemplate.getForObject(accessTokenUrl, AccessTokenInfo.class);

            // 数据库判断是否存在这个openid的用户
            Member user = memberService.getOne(new LambdaQueryWrapper<Member>()
                    .eq(Member::getOpenid, tokenInfo.getOpenid()));

            if (ObjectUtils.isEmpty(user)) {
                //3 拿着得到accsess_token 和 openid，再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //拼接两个参数
                String userInfoUrl = String.format(
                        baseUserInfoUrl,
                        tokenInfo.getAccess_token(),
                        tokenInfo.getOpenid()
                );
                //发送请求
                UserInfo userInfo = restTemplate.getForObject(userInfoUrl, UserInfo.class);

                // 保存用户信息
                user = new Member()
                        .setOpenid(userInfo.getOpenid())
                        .setNickname(userInfo.getNikename())
                        .setAvatar(userInfo.getHeadimgurl())
                        .setAge(userInfo.getSex() == 0 ? null : userInfo.getSex());

                memberService.save(user);
            }

            // 生成 token
            String token = JwtUtils.getJwtToken(user.getId(), user.getNickname());

            //最后：返回首页面，通过路径传递token字符串
            return "redirect:http://localhost:3000?token=" + token;
        }catch(Exception e) {
            e.printStackTrace();
            throw new GuLiException(20001,"登录失败");
        }
    }

    @GetMapping("login")
    public String getWxCode() {
        // 微信开放平台授权baseUrl  %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        //对redirect_url进行URLEncoder编码
        String redirectUrl = wxOpenProperties.getRedirectUrl();
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
        }catch(Exception e) {
            e.printStackTrace();
        }

        //设置%s里面值
        String url = String.format(
                    baseUrl,
                    wxOpenProperties.getAppId(),
                    redirectUrl,
                    "zhuhjay");

        //重定向到请求微信地址里面
        return "redirect:" + url;
    }
}
